<script setup>
import * as echarts from 'echarts/core'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LegendComponent
} from 'echarts/components'
import { LabelLayout, UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer,
  LegendComponent,
  PieChart
])
import { onBeforeUnmount, onMounted, reactive, watch } from 'vue'
import { chartsColors } from '@/utils/config.js'
import { formatNumber } from '@/utils/unit.js'
let chartInstance = null
const props = defineProps(['data', 'eid'])
const totals = props.data.seriesData.reduce(
  (accumulator, currentValue) => accumulator + currentValue.value,
  0
)

const option = reactive({
  color: chartsColors,
  tooltip: {
    trigger: 'item',
    textStyle: {
      fontSize: 10
    }
  },
  title: {},
  grid: {
    bottom: '20%' // 下边距
  },
  legend: {
    icon: 'circle',
    orient: 'vertical',
    align: 'left',
    top: 10,
    right: -10,
    // 使用formatter函数自定义图例的显示内容
    formatter: (name) => {
      const data = option.series[0].data
      const item = data.find((item) => item.name === name)
      if (item) {
        const percent =
          ((item.value === 0 ? 0 : item.value / totals) * 100).toFixed(0) + '%'
        return `\n ${name} ${percent} \n ${item.value}件`
      }
    },
    itemWidth: 14,
    itemGap: -5,
    // 设置图例的样式
    textStyle: {
      color: '#333',
      fontSize: 12,
      lineHeight: 16
    }
  },
  series: [
    {
      name: '',
      type: 'pie',
      center: ['30%', '45%'],
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 0,
        borderColor: '#fff',
        borderWidth: 0
      },
      label: {
        show: false,
        position: 'center'
      },
      labelLine: {
        show: false
      },
      data: props.data.seriesData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
})
const hasData = ref(false)
const centerText = reactive({
  title: '工单总数',
  value: '0',
  unit: '件'
})
onMounted(() => {
  chartInstance = echarts.init(document.getElementById(props.eid))
  updateChart()
  window.addEventListener('resize', canalDebounce)
})

watch(
  () => props,
  (newVal) => {
    option.series[0].data = newVal.data.seriesData
    updateChart()
  },
  { deep: true }
)

//页面销毁前，销毁事件和实例
onBeforeUnmount(() => {
  window.removeEventListener('resize', canalDebounce)
  // chartInstance.dispose()
})

const updateChart = () => {
  let temp = formatNumber(totals)
  centerText.value = temp.value
  centerText.unit = temp.unit
  hasData.value = !option.series[0].data || option.series[0].data.length === 0
  if (chartInstance) {
    chartInstance.setOption(option)
  }
}
const resizeHandler = () => {
  chartInstance.resize()
}
//设置防抖，保证无论拖动窗口大小，只执行一次获取浏览器宽高的方法
const debounce = (fun, delay) => {
  let timer
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fun()
    }, delay)
  }
}
const canalDebounce = debounce(resizeHandler, 500)
</script>

<template>
  <section class="flex justify-around w-full p-0 relative">
    <div
      class="absolute w-full h-full flex flex-col items-center justify-center box-border left-0 top-0 pr-35vw"
    >
      <template v-if="hasData">
        <p class="text-12px font-400 leading-17px text-#71747A">暂无数据</p>
      </template>
      <template v-else>
        <p
          class="text-12px font-400 leading-17px text-#71747A w-full text-center"
        >
          {{ centerText.title }}
        </p>
        <p class="text-18px font-700 leading-20px text-#1E2226 font-din">
          {{ centerText.value }}
        </p>
        <p class="text-12px font-400 leading-17px text-#71747A">
          {{ centerText.unit }}
        </p>
      </template>
    </div>
    <div :id="props.eid" class="flex-1 h-30vh z-90" />
  </section>
</template>

<style scoped>
p {
  margin: 0;
}
</style>
